#include "FlashDevice.h"
#include <vector>


using namespace std;
FlashDevice::FlashDevice(int size): _size(size)
{
	_extents = new map<string,int>();
}

FlashDevice::~FlashDevice(void)
{
	delete _extents;
}

void FlashDevice::updateExtents(map<string, int>* extents)
{
	// move the map into array
	int size = extents->size();
	if (size == 0) // first time
		return;
	pair<string,int>* data = new pair<string,int>[size];
	int ind = 0;
	for (map<string,int>::iterator it = extents->begin(); it != extents->end(); it++, ind++)
		data[ind] = *it;
	// sort the array (using bubble sort algorithm)
	pair<string,int> tmp; 
	for (int bubble = 0; bubble < size - 1; bubble++) {
		for (int index = 0; index < size - 1; index++) {
			if (data[index].second > data[index+1].second) { 
				tmp = data[index];
				data[index] = data[index+1]; 
				data[index+1] = tmp;
			}
		}
	}
	// clear previous extents from the device
	delete _extents;
	_extents = new map<string, int>();

	// add the extents with the most activity to the flash device
	for (int i = 0, j = size-1; i < _size && j >= 0; i++, j--)
		_extents->insert(data[j]);
	delete [] data;
}

bool FlashDevice::exist(std::string extentIO)
{
	return _extents->find(extentIO) != _extents->end();
}
